import requests
import os, sys, re
sys.path.append(r"D:/my_work/ac_lingxing_api/ac_lingxing_api")
from database.mysql_utils import MysqlUtils
from api_utils.email_send import email_send
import time, datetime
import pyautogui
import logging
from apscheduler.schedulers.blocking import BlockingScheduler

def update_ip(new_ip):
    db = MysqlUtils("rpa")
    cur = db.connection.cursor()
    sql = f"update xian_ip SET ip = '{new_ip}', update_time = '{datetime.datetime.now()}'"
    cur.execute(sql)
    db.connection.commit()
    cur.close()
    db.connection.close()

def get_ip():
    db = MysqlUtils("rpa")
    cur = db.connection.cursor()
    
    
    sql = "select ip from xian_ip"
    cur.execute(sql)
    result = cur.fetchall()[0][0]
    # cur.close()
    # db.connection.close()
    return result


def main():
    pyautogui.FAILSAFE = False

    LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
    logging.basicConfig(filename='D:/my_work/ac_lingxing_api/ac_lingxing_api/operation/ip_check.log', level=logging.DEBUG, format=LOG_FORMAT,encoding='UTF-8')
    logging.info(f"开始监控")
    while 1:
        result = get_ip()
        while 1:
            try:


                res= requests.get("https://toolbox.lingxing.com/api/getIp")
                if res.status_code != 200:
                    time.sleep(60)
                    continue
            except :
                continue
            
            ip_now = re.findall("[0-9]+.[0-9]+.[0-9]+.[0-9]+", res.json()["data"])[0]
            logging.info(f"{datetime.datetime.now()}, 当前数据库IP: {result}, 当前接口返回的IP：{ip_now}")
            if result != ip_now:
                update_ip(ip_now)
                pyautogui.hotkey('ctrl','shift', 'alt', 'h')
                logging.info(f"IP变化，新IP：{ip_now}")
                break
            time.sleep(60*5)
    

if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        logging.error(e)
    logging.info(f"退出程序")
